# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '11383852': {  # 乐酷支付 支付宝H5 2.5  微信扫码2.7 银联1.5  支付宝10-10000 微信45-5000 网银10-5000  witch
        'API_KEY': 'cIvzcteyyBuBQSfLCbqgkjaWYgLBJFlw',
        'PUB_KEY': 'EV3VTs8ox20ULztzssXbc6nz1KOzdjQP',
        'gateway': 'http://pay.shoukuan8.com/gateway',
        'query_gateway': 'http://pay.shoukuan8.com/Api/order',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['PUB_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(param, key):
    sign = 'appId=' + param['appId'] + '&appSecrect=' + key + '&merchTime=' \
           + param['merchTime'] + '&notifyUrl=' + param['notifyUrl'] + '&orderSn=' \
           + param['orderSn'] + '&payRemark=' + param['payRemark'] + '&payType=' \
           + param['payType'] + '&returnUrl=' + param['returnUrl'] + '&totalFee=' \
           + param['totalFee']
    return _gen_sign(sign)


def generate_notify_sign(param, key):
    sign = 'appId=' + param['appId'] + '&orderSn=' + param['orderSn'] + '&payTime=' + param['payTime'] + '&payType=' \
           + param['payType'] + '&pubSecrect=' + key + '&totalFee=' + param['totalFee']
    return _gen_sign(sign)


def verify_notify_sign(params, key):
    sign = params['paySign']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign:
        _LOGGER.info("lekupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


# 必填： 1.支付宝(包含扫码、H5)  2.微信(包含扫码、H5)  3.网银通道
def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    elif service == 'wxpay':
        return 'wxpay'
    elif service == 'bank':
        return 'bank'
    return 'alipay'


# 下单
def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('appId', app_id),
        ('payType', _get_pay_type(service)),
        ('orderSn', str(pay.id)),
        ('totalFee', '%.2f' % pay_amount),
        ('merchTime', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('returnUrl', '{}/pay/api/{}/lekupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyUrl', '{}/pay/api/{}/lekupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('payRemark', 'charge'),
        ('getAjax', '1'),
    ))
    parameter_dict['paySign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lekupay create: %s, order_id is:%s ", json.dumps(parameter_dict),
                 parameter_dict['orderSn'])
    if _get_pay_type(service) == 'bank':
        html_text = _build_form(parameter_dict, _get_gateway(app_id))
        cache_id = redis_cache.save_html(pay.id, html_text)
        _LOGGER.info('lekupay url: %s', settings.PAY_CACHE_URL + cache_id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    elif _get_pay_type(service) == 'alipay':
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
        _LOGGER.info("lekupay create rsp data: %s %s", response.status_code, response.text)
        return {'charge_info': json.loads(response.text)['info']}


# 通知
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("lekupay notify data: %s", data)
    api_key = _get_pub_key(data['appId'])
    verify_notify_sign(data, api_key)
    pay_id = data['orderSn']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('lekupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['orderSn']
    total_fee = float(data['totalFee'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    _LOGGER.info('lekupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


# 查询
def query_charge(pay_order, app_id):
    api_key = _get_pub_key(app_id)
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('pubsecrect', api_key),
        ('out_trade_no', str(pay_order.id)),
    ))
    _LOGGER.info("lekupay query data: %s, order_id is: %s ", parameter_dict, parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("lekupay query  rsp data: %s,%s", response.text, response.url)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['code'])
        total_fee = float(pay_order.total_fee)
        trade_no = pay_order.third_id

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 订单状态：2 支付完成
        if trade_status == '2':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('lekupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
